<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	</head>
	<body>
	<h1>Pick Contacts</h1>
	<button id="accept">Accept</button>
	<button onclick="window.close()">Cancel</button>
	<?php
		$test = $this->widget('zii.widgets.grid.CGridView', array(
			'id'=>'cm-contact-grid',
			'dataProvider'=>$dataProvider,
			'selectableRows' => 10,
			'rowHtmlOptionsExpression' => 'array("rowid" => "$data->id")',
			'columns'=>array(
				array(
					'class' => 'CCheckBoxColumn',
					'selectableRows' => null
				),
				'last_name',
				'first_name',		
				'email' => array(
					'id' => 'emailz',
					'sortable' => false,
					'name' => 'email'
				),
				array(
					'name' => 'bestPhone',
					'type' => 'raw',
					'value' => '$data->details->getBestPhone()'
				),
			),
			'ajaxUpdate' => false,
	)); ?>
	<script src="<?php echo Yii::app()->request->baseUrl; ?>/js/jquery-1.9.1.min.js"></script>
	<?php
	Yii::app()->clientScript->registerScript('cm-contact-grid', "
		var grid = $('div#cm-contact-grid');
		if (localStorage['cm_pick_grid']) {
			var ls = JSON.parse(localStorage['cm_pick_grid']);
			$('table.items input.select-on-check');
			for (var i in ls) {
				grid.find('tr[rowid=' + i + ']').trigger('click');
			}
		}
		var save_storage = function(){			
			var selected = grid.yiiGridView('getSelection');
			var local_storage = {};			
			if (localStorage['cm_pick_grid']) {
				local_storage = JSON.parse(localStorage['cm_pick_grid']);
				var rows = grid.find('tr');
				var value;
				$.each(rows, function(){
					value = $(this).attr('rowid');
					if(value in local_storage && selected.indexOf(value) == -1) {
						delete local_storage[value];
					}
				});
			}
			for (var i in selected) {
				if(!(selected[i] in local_storage)) {
					local_storage[selected[i]] = grid.find('tr[rowid=' + selected[i] + ']').children()[3].innerHTML;
				}
			}				
			localStorage['cm_pick_grid'] = JSON.stringify(local_storage);
			console.log(JSON.parse(localStorage['cm_pick_grid']));
			return true;
		}
		$('a', $('ul.yiiPager')).bind('click', save_storage);
		$('table.items thead tr th a').bind('click', save_storage);
		
		$('button#accept').click(function(){			
			if (localStorage['cm_pick_grid']) {
				var local_storage = JSON.parse(localStorage['cm_pick_grid']);
				var emails = [];
				for (var i in local_storage) {
					emails.push(local_storage[i]);				
				}
				var emailStr = emails.join(', ');
				var toField = window.opener.document.getElementById('toField');
				if (toField.value.length > 0) {
					emailStr = ', ' + emailStr;
				}
				toField.value += emailStr;
			}
			window.close();
			return false;
		});
	", CClientScript::POS_READY);
	?>
	</body>	
</html>